package com.hrms.common.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.hrms.common.exception.BusinessException;
import com.hrms.common.utils.SecurityUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 自动填充处理类
 * @author badao
 * @version 1.0
 * @see
 **/
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    // 使用 ThreadLocal 控制填充开关（默认开启）
    private static final ThreadLocal<Boolean> FILL_ENABLED = ThreadLocal.withInitial(() -> true);
    // 关闭自动填充
    public static void disableFill() {
        FILL_ENABLED.set(false);
    }

    // 开启自动填充
    public static void enableFill() {
        FILL_ENABLED.set(true);
    }
    @Override
    public void insertFill(MetaObject metaObject) {
        if (!FILL_ENABLED.get()) return;
        try {
            String s = (String) metaObject.getValue("createdBy");
            if (s == null){
                String username = SecurityUtils.getCurrentUsername();
                this.setFieldValByName("createdBy",username , metaObject);
            }
            this.setFieldValByName("createdOn", new Date(), metaObject);
        } catch (BusinessException e) {
            throw new RuntimeException(e);
        }
    }
 
    @Override
    public void updateFill(MetaObject metaObject) {
        if (!FILL_ENABLED.get()) return;
        try {
            String s = (String) metaObject.getValue("lastModifiedBy");
            if (s == null){
                String username = SecurityUtils.getCurrentUsername();
                this.setFieldValByName("lastModifiedBy", username, metaObject);
            }
            this.setFieldValByName("lastModifiedOn", new Date(), metaObject);
        } catch (BusinessException e) {
            throw new RuntimeException(e);
        }
    }
}